public class Solution1 {
    public boolean[][] visit;
    public int m;
    public int n;
    public char[] word;

    public boolean exist(char[][] board, String _word) {
        m = board.length;
        n = board[0].length;
        word = _word.toCharArray();
        visit = new boolean[m][n];

        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(board[i][j] == word[0]) {
                    visit[i][j] = true;
                    if(dfs(board,i,j,1)) {
                        return true;
                    }
                    visit[i][j] = false;
                }
            }
        }
        return false;
    }

    public int[] dx = {0, 0, 1, -1};
    public int[] dy = {1, -1, 0, 0};

    public boolean dfs(char[][] board,int i, int j, int pos) {
        if(pos == word.length) {
            return true;
        }

        // 利用向量组，一个for循环搞定上下左右四个方向
        for(int k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && visit[x][y] == false && board[x][y] == word[pos]) {
                visit[x][y] = true;
                if(dfs(board, x, y, pos + 1)) {
                    return true;
                }
                visit[x][y] = false;
            }
        }
        return false;
    }
}
